package org.wyw.solution;

import java.util.Stack;

@Solution(
        id = 6,
        title = "有效的括号",
        difficulty = "medium",
        link = "https://leetcode.cn/problems/valid-parentheses/description/"
)
public class Solution006 {

    public boolean isValid(String s) {
        char[] charArray = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (int j = 0; j < charArray.length; j++) {
            if (charArray[j] == '('){
                stack.push(')');
            }else if (charArray[j] == '['){
                stack.push(']');
            }else if (charArray[j] == '{'){
                stack.push('}');
            }else {
                //若是右括号：1.若栈为空，说明没有左括号，字符串是无效括号。2.若栈不为空，弹出栈顶元素，若当前右括号不是栈顶元素，是无效括号
                if (stack.isEmpty() || charArray[j] != stack.pop()){
                    return false;
                }
            }
        }
        //若栈为空，说明元素全部弹出且匹配
        return stack.isEmpty();
    }

}
